package com.javalearn.gulimail.product.web;

import com.javalearn.gulimail.product.entity.CategoryEntity;
import com.javalearn.gulimail.product.service.CategoryService;
import com.javalearn.gulimail.product.vo.Catelog2Vo;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
public class IndexController {

    @Autowired
    CategoryService categoryService;

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @GetMapping({"/","/index.html"})
    public String indexPage(Model model){

        //TODO 查询所有的1级分类
        List<CategoryEntity> categoryEntities = categoryService.getLevel1Categorys();

        //视图解析器进行拼串，回顾一下mvc，视图解析器的已经完成了自动配置
        model.addAttribute("categorys",categoryEntities);
        return "index";
    }

    @ResponseBody //将返回值以json的方式写出去
    @GetMapping("/index/catalog.json")
    public Map<String, List<Catelog2Vo>> getCatelogJson(){
        Map<String, List<Catelog2Vo>> catelogJson = categoryService.getCatelogJson();
        return catelogJson;
    }

    @ResponseBody
    @GetMapping("/hello")
    public String hello(){
        //1.获取一把锁，只要锁的名字一样，就是同一把所
        RLock lock = redissonClient.getLock("my-lock");

        //2.加锁
        lock.lock();//如果拿不到锁，就会一直等待

        //1.如果传递了锁的超时时间，就发送给redis执行脚本，默认超时就是我们指定的时间
        //如果未指定锁的超时时间，就是用LockWatchDog的默认时间30秒，只要占锁成功，就会启动一个定时任务，（周期为1/3个看门狗时间，到了就会重新设置过期时间，新的过期时间就是看门狗时间）
//        lock.lock(10, TimeUnit.SECONDS);//10秒钟自动解锁，注意，自动解锁时间一定要大于业务处理时间，如果锁时间超时了，不会续期，而是抛出异常
        try {
            System.out.println("加锁成功，执行业务"+Thread.currentThread().getId());
            Thread.sleep(30000);
        } catch (InterruptedException e) {

        } finally {
            //解锁  假设解锁代码没有运行，Redisson也不会出现死锁
            System.out.println("释放锁......"+Thread.currentThread().getId());
            lock.unlock();
        }
        return "hello";
    }

    @GetMapping("/write")
    @ResponseBody
    public String writeValue(){
        RReadWriteLock lock = redissonClient.getReadWriteLock("rw-lock");
        //写锁
        RLock rLock = lock.writeLock();
        String s = "";
        rLock.lock();
        System.out.println("写锁加载成功"+Thread.currentThread().getId());
        try {
            s=UUID.randomUUID().toString();
            Thread.sleep(30000);
            stringRedisTemplate.opsForValue().set("writeValue",s);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            rLock.unlock();
            System.out.println("写锁释放"+Thread.currentThread().getId());
        }
        return s;
    }

    @GetMapping("/read")
    @ResponseBody
    public String readValue(){
        RReadWriteLock lock = redissonClient.getReadWriteLock("rw-lock");
        //读锁
        RLock rLock = lock.readLock();
        String s = "";
        rLock.lock();
        System.out.println("读锁加载成功"+Thread.currentThread().getId());
        try {
            s = stringRedisTemplate.opsForValue().get("writeValue");
            Thread.sleep(30000);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            rLock.unlock();
            System.out.println("读锁释放"+Thread.currentThread().getId());
        }
        return s;
    }

    /**
     * 车库停车
     * 3车位
     */
    @ResponseBody
    @GetMapping("/park")
    public String park() throws InterruptedException {
        RSemaphore park = redissonClient.getSemaphore("park");
//        park.acquire();//获取一个信号值，占一个车位
        boolean b = park.tryAcquire();//尝试获取
        if (b){
            //执行业务
        }else {
            System.out.println("当前流量过大！");
        }

        return "ok"+b;
    }

    @ResponseBody
    @GetMapping("/go")
    public String go() throws InterruptedException {
        RSemaphore park = redissonClient.getSemaphore("park");
        park.release();//获取一个信号值，释放一个车位

        return "ok";
    }

    /**
     * 放假锁门
     * 班级人走完才能锁门
     * 假设要等待五个班走完才能锁门
     */
    @GetMapping("loclDoor")
    public String lockDoor() throws InterruptedException {
        RCountDownLatch door = redissonClient.getCountDownLatch("door");
        door.trySetCount(5);
        door.await();//等待闭锁完成
        return "放假了";
    }

    @GetMapping("/gogogo/{id}")
    public String gogogo(@PathVariable("id") Long id){
        RCountDownLatch door = redissonClient.getCountDownLatch("door");
        door.countDown();//计数减1
        return id+"班的人都走了";
    }
}
